package visiopuce.action;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import visiopuce.ICommandIds;
import visiopuce.objets.Personne;
import visiopuce.objets.Prelevement;
import visiopuce.ui.DossierEditorInput;
import visiopuce.ui.NouveauPrelevementDialog;
import visiopuce.ui.view.DossierEditor;

public class CreerPrelevementAction extends Action {
	private final IWorkbenchWindow window;

	public CreerPrelevementAction(IWorkbenchWindow window, String label) {
		this.window = window;
		setText(label);
		// The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_CREER_PRELEVEMENT);
		// Associate the action with a pre-defined command, to allow key
		// bindings.
		setActionDefinitionId(ICommandIds.CMD_CREER_PRELEVEMENT);
		setText("Créer un prélèvement");
		setImageDescriptor(visiopuce.Activator.getImageDescriptor("/icons/prelevement_plus.png"));
	}

	public void run() {
		NouveauPrelevementDialog nouveauPrelevementDialog = new NouveauPrelevementDialog(window.getShell());
		if (nouveauPrelevementDialog.open() == IDialogConstants.OK_ID) {
			try {
				Personne personne = nouveauPrelevementDialog.getPersonneAssociee();

				IEditorInput editorInput = new DossierEditorInput(personne.getIdPersonne());
				PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(editorInput, DossierEditor.ID, true, IWorkbenchPage.MATCH_INPUT);
				// A faire aller sur la page du nouveau prélèvement
				DossierEditor dossierEditor = (DossierEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
				Prelevement newPrelevement = new Prelevement();
				newPrelevement.setIdPrelevement(0);
				newPrelevement.setPersonne(personne);
				dossierEditor.addPrelevementTabItem(newPrelevement);
			} catch (PartInitException e) {
				MessageDialog.openError(window.getShell(), "Error", "Erreur lors de l'ouverture de la page du prélèvement" + e.getMessage());
			}
		}

	}
}